﻿using AutoMapper;
using B.S.BaseData.Domain.Entities;
using B.S.BaseData.ErrorCode;
using B.S.BaseData.Infrastructure.Interfaces;
using B.S.BaseData.Write.API.Command.MenuCommand;
using MediatR;

namespace B.S.BaseData.Write.API.CommandHandler.MenuHandler
{
    public class CreateMenuHandler : IRequestHandler<CreateMenuCommand, APIResult<int>>
    {
        private readonly IBaseRepository<Menu> menuRep;
        private readonly IMapper mapper;

        public CreateMenuHandler(IBaseRepository<Menu> menuRep,IMapper mapper)
        {
            this.menuRep = menuRep;
            this.mapper = mapper;
        }
        public async Task<APIResult<int>> Handle(CreateMenuCommand request, CancellationToken cancellationToken)
        {
            APIResult<int> result = new APIResult<int>();
            var entity=mapper.Map<Menu>(request);
            var name=menuRep.GetAllAsync().Result.Where(x=>x.PId==request.PId&&x.MenuName==request.MenuName);
            if (name.Count()>0)
            {

                result.Code = APIEnum.Failed;
                result.Msg = $"同一级菜单下已存在{request.MenuName}的名称,请重新添加";
                result.Data = 0;
                return await Task.FromResult(result);
            }

            entity.CreateUser = "admin";
            entity.CreateTime = DateTime.Now;
            entity.UpdateUser = "";
            entity.IsDeleted = false;
         
                await menuRep.AddAsync(entity);
                result.Code=APIEnum.Success;
                result.Msg = "添加成功";
                result.Data = 1;
       
            return await Task.FromResult(result);

        }
    }
}
